package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
//            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            //存储验证码,登录时比较验证
//            session.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {
        //获取手机号和验证码
        String phone= map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取保存的验证码,比对
//        String codeSession = (String) session.getAttribute(phone);
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        //验证通过登陆成功
        if (code!=null&&code.equals(codeInSession)){
            //查找手机号是否在user表,不在则是新用户,添加到user
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User loginUser = userService.getOne(lqw);
            if (loginUser==null){
                //新用户,自动注册
                loginUser=new User();
                loginUser.setPhone(phone);
                loginUser.setStatus(1);
                userService.save(loginUser);
            }
            session.setAttribute("user",loginUser.getId());
            //登录成功,从Redis中删除缓存的验证码
            redisTemplate.delete(phone);
            return R.success(loginUser);
        }
        return R.error("登录失败");
    }


    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
